package com.zone.gateway.core.socket.handler;

import com.zone.gateway.core.bind.IGenericReference;
import com.zone.gateway.core.executor.result.SessionCode;
import com.zone.gateway.core.executor.result.SessionResult;
import com.zone.gateway.core.session.GatewaySession;
import com.zone.gateway.core.session.GatewaySessionFactory;
import com.zone.gateway.core.socket.BaseHandler;
import com.zone.gateway.core.socket.agreement.*;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author: zongzi
 * @description: TODO
 * @date: 2025/4/23
 */
public class ProtoDataHandler extends BaseHandler<FullHttpRequest> {
    private final Logger logger = LoggerFactory.getLogger(GatewayChannelHandler.class);

    private final GatewaySessionFactory gatewaySessionFactory;

    public ProtoDataHandler(GatewaySessionFactory gatewaySessionFactory) {
        this.gatewaySessionFactory = gatewaySessionFactory;
    }

    @Override
    protected void session(ChannelHandlerContext ctx, Channel channel, FullHttpRequest request) {
        logger.info("网关已经接口到请求 uri = {} method = {}", request.getUri(), request.getMethod());

        RequestParserDirector requestParserDirector = new RequestParserDirector(request);
        // 解析请求参数
        Map<String, Object> args;
        try {
            IRequestParser requestParser = requestParserDirector.getParser();
            args = requestParser.analysis(request);
        } catch (Exception e) {
            logger.error("请求参数解析失败", e);
            GatewayResultMessage errorMsg = GatewayResultMessage.newInstant(AgreementConstant.ResponseCode._400, "参数解析失败" + e.getMessage());
            DefaultFullHttpResponse errorResponse = ResponseParser.createResponse(errorMsg);
            channel.writeAndFlush(errorResponse);
            request.release();
            return;
        }

        // 解析uri
        String uri = requestParserDirector.getUri();

        // 调用rpc泛化服务获取返回值
        GatewaySession gatewaySession = gatewaySessionFactory.openSession(uri);
        IGenericReference genericReference = gatewaySession.getMapped();
        SessionResult sessionResult = genericReference.$invoke(args);
        GatewayResultMessage gatewayResultMessage = SessionCode.SUCCESS.getCode().equals(sessionResult.getCode())
                ? GatewayResultMessage.success(sessionResult.getResult())
                : GatewayResultMessage.newInstant(AgreementConstant.ResponseCode._500, sessionResult.getResult());

        DefaultFullHttpResponse response = ResponseParser.createResponse(gatewayResultMessage);
        channel.writeAndFlush(response);
    }
}
